package hn.cch.framework.http;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.security.KeyStore;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

public class HttpsUtil {

    private static final Logger logger = LoggerFactory.getLogger(HttpsUtil.class);

    //字符集
    private static String charset = "utf-8";


    private static X509TrustManager manager = null;

    public static void initX509(String keystore, String password) {
        try {
            KeyStore keyStore = KeyStore.getInstance("JKS");
            keyStore.load(new FileInputStream(keystore), password.toCharArray());
            TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance("SunX509", "SunJSSE");
            trustManagerFactory.init(keyStore);
            TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();

            for (int i = 0; i < trustManagers.length; i++) {
                if (trustManagers[i] instanceof X509TrustManager) {
                    manager = (X509TrustManager) trustManagers[i];
                    break;
                }
            }
            if (manager == null) {
                throw new Exception("manager null ");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public static byte[] sentPost(String url, byte[] request) {
        byte[] response = null;
        OutputStream outputStream = null;
        InputStream inputStream = null;

        try {


            SSLContext sslContext = SSLContext.getInstance("JKS");
            // SSLContext sslContext = SSLContext.getInstance("TLS");
            // SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");

            sslContext.init(null, new TrustManager[]{new X509TrustManager() {

                @Override
                public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
                    manager.checkClientTrusted(x509Certificates, s);
                }

                @Override
                public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
                    // manager.checkServerTrusted(x509Certificates, s);
                }

                @Override
                public X509Certificate[] getAcceptedIssuers() {
                    return manager.getAcceptedIssuers();
                }
            }}, new SecureRandom());


            SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
            HttpsURLConnection.setDefaultSSLSocketFactory(sslSocketFactory);

            HostnameVerifier hostnameVerifier = new HostnameVerifier() {
                @Override
                public boolean verify(String s, SSLSession sslSession) {
                    return true;
                }
            };
            HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier);


            HttpsURLConnection httpsURLConnection = (HttpsURLConnection) new URL(url).openConnection();

            httpsURLConnection.setDoInput(true);
            httpsURLConnection.setDoOutput(true);
            // 关闭缓存
            httpsURLConnection.setUseCaches(false);
            // 开启长连接
            httpsURLConnection.setRequestProperty("Connection", "Keep-Alive");
            // 超时时间设置
            httpsURLConnection.setConnectTimeout(1000);
            httpsURLConnection.setReadTimeout(30 * 1000);


            httpsURLConnection.setSSLSocketFactory(sslSocketFactory);
            httpsURLConnection.setHostnameVerifier(hostnameVerifier);
            // 不允许重定向
            httpsURLConnection.setInstanceFollowRedirects(false);


            //读写
            logger.info("OutputStream write");
            outputStream = httpsURLConnection.getOutputStream();
            outputStream.write(request);

            logger.info("InputStream read");
            inputStream = httpsURLConnection.getInputStream();

            response = new byte[httpsURLConnection.getContentLength()];
            int contentLength = inputStream.read(response);
            logger.info("ContentLength " + contentLength);


        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 关闭
            try {
                if (outputStream != null) {
                    outputStream.close();
                }
                if (inputStream != null) {
                    inputStream.close();
                }
                logger.info("Stream close success");
            } catch (IOException e) {
                logger.error("Stream close fail");
                //e.printStackTrace();
            }
        }
        return response;


    }


}

